package me.zhengjie.init;


import me.zhengjie.common.DlaServerConfig;
import me.zhengjie.util.MapUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Component
public class InitUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitUtil.class);
    private static final String PROPERTY_FILENAME = "config.properties";
    private static final String SQL_FILE_PATH = "sql/*.sql";

    @Autowired
    DlaServerConfig config;
    @Autowired
    DataSource dataSource;
    @PostConstruct
    public void init() throws Exception {
        Properties properties = loadProperties();
        config.setDLAConfig(properties);
        //createTables();
    }

    private  void createTables()  {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            for (Map<String, String> loadSqlFile : loadSqlFiles()) {
                jdbcTemplate.update(loadSqlFile.get("sql"));
                LOGGER.info("表：{} 创建成功",loadSqlFile.get("fileName").split("\\."));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private  Properties loadProperties() throws IOException {
        LOGGER.info("Loading config properties file");
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTY_FILENAME);
        Properties properties = new Properties();
        properties.load(inputStream);
        return properties;
    }

    private  List<Map<String, String>> loadSqlFiles() {
        List<Map<String, String>> sqlMapList = new ArrayList<>();
        LOGGER.info("加载 sql 脚本文件");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources(SQL_FILE_PATH);
            for (Resource resource : resources) {
                String fileName = resource.getFilename();
                InputStream inputStream = resource.getInputStream();
                String sql = IOUtils.toString(inputStream, "UTF-8");
                sqlMapList.add(MapUtil.of("fileName", fileName, "sql", sql));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlMapList;
    }
}
